/*
 *this file is part of nseer erp
 *Copyright (C)2006-2010 Nseer(Beijing) Technology co.LTD/http://www.nseer.com 
 *
 *This program is free software; you can redistribute it and/or
 *modify it under the terms of the GNU General Public License
 *as published by the Free Software Foundation; either
 *version 2 of the License, or (at your option) any later version.
 */
package include.data_backup;

import java.io.*;
import java.net.*;
import java.util.Properties;

public class MysqlStore {

	private Runtime rt;
	private PropertiesReader reader;
	private String fileName;
	private String userName;
	private String password;
	private String strURL1;

	public MysqlStore() {
		reader = new PropertiesReader();
		userName = reader.getProperty("username");
		password = reader.getProperty("password");
		String strClassName = getClass().getName();
		String strPackageName = "";
		if (getClass().getPackage() != null) {
			strPackageName = getClass().getPackage().getName();
		}
		String strClassFileName = "";
		if (!"".equals(strPackageName)) {
			strClassFileName = strClassName.substring(
					strPackageName.length() + 1, strClassName.length());
		} else {
			strClassFileName = strClassName;
		}
		URL url = getClass().getResource(strClassFileName + ".class");
		String strURL = url.toString();
		strURL = strURL.substring(strURL.indexOf('/') + 1, strURL
				.lastIndexOf('/'));
		String strURL2 = strURL.substring(0, strURL.lastIndexOf("WEB-INF"));
		strURL1 = strURL2 + "WEB-INF/";
		try {
			rt = Runtime.getRuntime();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public boolean backup(String fileName, String database) {
		fileName = getBackupFileName(fileName);
		try {
			Properties properties = new Properties();
			InputStream inputstream = getClass().getClassLoader()
					.getResourceAsStream("/conf/dbip.properties");
			properties.load(inputstream);
			if (inputstream != null) {
				inputstream.close();
			}
			String masterIp = properties.getProperty("IP");
			Process process = rt.exec("mysqldump  -x  -u" + userName + " -p"
					+ password
					+ " -c --default-character-set=utf8  --databases "
					+ database + " -h " + masterIp + " ");
			String line = "";
			BufferedWriter bufferedWriter = new BufferedWriter(
					new OutputStreamWriter(new FileOutputStream(fileName),
							"UTF-8"));
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(process.getInputStream(), "UTF-8"));
			while ((line = bufferedReader.readLine()) != null) {
				bufferedWriter.write(line.replace("text NOT NULL,",
						"text NOT NULL default '',"));
				bufferedWriter.newLine();
			}
			bufferedWriter.flush();
			bufferedWriter.close();
			process.waitFor();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} catch (InterruptedException ie) {
			ie.printStackTrace();
			return false;
		}
		return true;
	}

	public boolean recovery(String fileName) {
		String btfileName = writeHelperBat(fileName);
		try {
			Process process = null;
			String os = System.getProperties().getProperty("os.name");
			if (os.equals("Linux")) {
				CmdExec("chmod +x " + btfileName);
				process = rt.exec(btfileName);
			} else {
				process = rt.exec("cmd /E:OFF /c start " + btfileName);
			}
			String line = "";
			BufferedReader bufferedReader = new BufferedReader(
					new InputStreamReader(process.getInputStream()));
			while ((line = bufferedReader.readLine()) != null) {
				System.out.println(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	private String getBackupFileName(String fileName) {
		String time = getTime();
		int index = fileName.lastIndexOf(".");
		if (index != -1) {
			fileName = fileName.substring(0, index)
					+ fileName.substring(index, fileName.length());
		} else {
			fileName = fileName;
		}
		fileName = strURL1 + fileName;
		return fileName;
	}

	private String getRecoveryFileName(String fileName) {
		if (System.getProperties().getProperty("os.name").equals("Linux")) {
			fileName = strURL1 + fileName;
		} else {
			fileName = strURL1.substring(1, strURL1.length()) + fileName;
		}
		return fileName;
	}

	private String getTime() {
		java.util.Date now = new java.util.Date();
		java.text.SimpleDateFormat formater = new java.text.SimpleDateFormat(
				"yy-MM-dd-hh-mm-ss");
		String time = formater.format(now);
		return time;
	}

	private String writeHelperBat(String fileName) {
		String btfile = getRecoveryFileName("do.bat");
		fileName = getRecoveryFileName(fileName);
		File file = new File(btfile);
		if (file.exists()) {
			file.delete();
		}
		try {
			Properties properties = new Properties();
			InputStream inputstream = getClass().getClassLoader()
					.getResourceAsStream("/conf/dbip.properties");
			properties.load(inputstream);
			if (inputstream != null) {
				inputstream.close();
			}
			String masterIp = properties.getProperty("IP");
			BufferedWriter bufferedWriter = new BufferedWriter(
					new OutputStreamWriter(new FileOutputStream(btfile)));
			String content = "mysql -u" + userName + " -p" + password + " -h "
					+ masterIp + " <" + fileName;
			bufferedWriter.write(content);
			bufferedWriter.newLine();
			bufferedWriter.write("exit");
			bufferedWriter.flush();
			bufferedWriter.close();
		} catch (FileNotFoundException fe) {
			fe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
		return btfile;
	}

	public void CmdExec(String cmdline) {
		try {
			String line;
			Process p = null;
			if (p != null) {
				p.destroy();
				p = null;
			}
			p = Runtime.getRuntime().exec(cmdline);
			BufferedReader input = new BufferedReader(new InputStreamReader(p
					.getInputStream()));
			line = input.readLine();
			while (line != null) {
				line = input.readLine();
			}
			input.close();
			p.waitFor();
			int ret = p.exitValue();
		} catch (Exception err) {
			err.printStackTrace();
		}
	}

	public static void main(String[] args) {
		MysqlStore store = new MysqlStore();
		store.recovery("backm.sql");
	}
}
